<template>
  <div id="app"
       @drop="drop"
       @dragover="dragover"
       @dragenter="dragenter"
       @dragleave="dragleave">
    <div class="app_header drag"
         v-if="!isPreview"></div>
    <div class="app_content"
         :style="appContentStyles">
      <Tabs style="height: 100%;"
            name="tabs"
            v-model="activeTab">
        <TabPane v-for="(item, index) in tabs"
                 :key="index"
                 tab="tabs"
                 :name="item.name"
                 :icon="item.icon"
                 :label="item.label">
          <component :is="item.component"
                     :active-tab="activeTab"
                     :url-params="urlParams || {}"
                     @tab-change="changeTab"></component>
        </TabPane>
      </Tabs>
    </div>
    <all-svgs></all-svgs>

    <transition name="fade">
      <div class="overlay_container"
           key="Package"
           v-if="showOverlay && (['Package', 'Developer'].indexOf(activeTab) > -1)">
        <DragoverOverlay :step="dropStep"
                         :files="dropFiles"
                         :accept="activeTab == 'Package' ? 'bbt' : 'bbc'"
                         @hide="hideDropOverlay"></DragoverOverlay>
      </div>
    </transition>
  </div>
</template>

<script>
import { Tabs, TabPane } from 'view-design'
import AutoUpgrade from './worker/auto_upgrade.worker'
import { createNamespacedHelpers, mapState } from 'vuex'
const { mapActions } = createNamespacedHelpers('./store/modules')
export default {
  name: 'App',
  components: {
    TabPlugins: () => import('./components/Plugins'),
    TabInstalled: () => import('./components/Installed'),
    TabPackage: () => import('./components/Package'),
    TabDeveloper: () => import('./components/Developer'),
    TabProfile: () => import('./components/Profile/index'),
    TabReview: () => import('./components/Review'),
    TabSettings: () => import('./components/Settings/index'),
    AllSvgs: () => import('./Svgs.vue'),
    DragoverOverlay: () => import('./components/widgets/DragoverOverlay/index'),
    Tabs, TabPane
  },
  data () {
    return {
      activeTab: 'Plugins',
      urlParams: {},
      // loginInfo: {},
      dragendEle: null,
      showOverlay: false,
      dropStep: 0,
      dropFiles: [],
      settings: {},
      autoUpgrade: new AutoUpgrade(),
      upgradeList: {}, // 正在自动更新的插件
      isPreview: bbtools.isPreview
    }
  },
  watch: {
    installedPlugins: {
      deep: true,
      handler (val) {
        this.autoUpgrade && this.autoUpgrade.postMessage({
          event: 'set-installed-plugins',
          data: {
            list: val || []
          }
        })
      }
    }
  },
  computed: {
    ...mapState(
      {
        loginInfo: (state) => state.moduleUser.userInfo,
        installedPlugins: (state) => state.modulePlugins.normal,
        needUpgrade: (state) => state.modulePlugins.needUpgrade,
        downloading: (state) => state.modulePlugins.downloading
      }
    ),
    tabs () {
      let _tabs = [
        {
          label: '插件中心',
          name: 'Plugins',
          icon: 'ios-apps',
          component: 'TabPlugins'
        },
        {
          label: '已安装',
          name: 'Installed',
          icon: 'ios-thumbs-up',
          component: 'TabInstalled'
        },
        {
          label: '开发者',
          name: 'Developer',
          icon: 'ios-bug',
          component: 'TabDeveloper'
        },
        {
          label: '用户中心',
          name: 'Profile',
          icon: 'ios-contact',
          component: 'TabProfile'
        },
      ]
      if (this.loginInfo && this.loginInfo.token && (this.loginInfo.role == '0d883eff-d6ae-4992-9f11-848f8aa9c61c')) {
        _tabs.push({
          label: '审核管理',
          name: 'Review',
          icon: 'ios-film',
          component: 'TabReview'
        })
      }
      _tabs.push({
        label: '设置',
        name: 'Settings',
        icon: 'ios-settings',
        component: 'TabSettings'
      })
      _tabs.push({
        label: '本地安装包',
        name: 'Package',
        icon: 'ios-briefcase',
        component: 'TabPackage'
      })
      return _tabs
    },
    appContentStyles () {
      if (this.isPreview) {
        return {
          height: '100%'
        }
      } else {
        return {
          height: 'calc(100% - 36px)'
        }
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      let query = this.$urlFormat()
      if (query.hasOwnProperty('tab')) {
        this.activeTab = query['tab'] || 'Plugins'
      }
      this.$store.dispatch('moduleUser/init')

      this.$store.dispatch('modulePlugins/init')

      bbtools.send('shortcut-create', {
        keys: ['CommandOrControl', 'P'],
        author: 'bbtlovesyou',
        action: 'navigate',
        name: 'openPluginCenter',
        desc: '打开插件中心',
        settings: {
          pid: 'bbtlovesyou'
        }
      })

      bbtools.on('plugin-list-response', this.pluginListResponse)
      bbtools.send('plugin-list')

      bbtools.on('user-register-response', this.userRegisterResponse)
      bbtools.on('user-login-response', this.userLoginResponse)
      bbtools.on('user-logout-response', this.userLogoutResponse)
      bbtools.on('plugin-pack-response', this.pluginPackResponse)
      bbtools.on('plugin-reload-response', this.pluginReloadResponse)
      bbtools.on('drop-file-bbc-response', this.dropFileBbcResponse)
      bbtools.on('drop-file-bbt-response', this.dropFileBbtResponse)
      bbtools.on('category-list-response', this.categoryListResponse)

      bbtools.on('plugin-install-response', this.pluginInstallResponse)
      bbtools.on('plugin-remove-response', this.pluginRemoveResponse)
      bbtools.on('plugin-upgrade-response', this.pluginUpgradeResponse)
      bbtools.on('plugin-uninstall-response', this.pluginUninstallResponse)

      this.autoUpgrade.addEventListener('message', this.autoUpgradeHandler)
      // })
    })
    // setTimeout(() => {
    //   bbtools.on('filter-changed', this.filterChanged)
    // }, 100)
  },
  methods: {
    ...mapActions([
      'moduleInstalled',
      'modulePlugins',
      'moduleUser',
    ]),
    userRegisterResponse (event, response) {
      if (response.code == 200) {
        this.$Message.success({
          content: '注册成功, ' + (response.data.nickname || response.data.username),
          duration: 5,
          background: true
        })
      } else {
        this.$Message.error({
          content: response.errmsg || '注册失败,请稍后再试',
          duration: 5,
          background: true
        })
      }
    },
    userLoginResponse (event, response) {
      if (response.code == 200) {
        this.$Message.success({
          content: '登录成功, ' + (response.data.nickname || response.data.username),
          duration: 5,
          background: true
        })
        this.$store.dispatch('moduleUser/login', response.data)
      } else {
        this.$Message.error({
          content: response.errmsg || '登录失败,请稍后再试',
          duration: 5,
          background: true
        })
      }
    },
    userLogoutResponse (event, response) {
      if (response.code == 200) {
        this.$Message.success({
          content: '退出成功',
          duration: 5,
          background: true
        })
        this.$store.dispatch('moduleUser/logout')
      } else {
        this.$Message.error({
          content: response.errmsg || '退出失败,请稍后再试',
          duration: 5,
          background: true
        })
      }
    },
    pluginPackResponse (event, response) {
      if (response.code != 200) {
        this.$Message.error({
          content: response.errmsg || '打包失败,请稍后再试',
          duration: 5,
          background: true
        })
      } else {
        this.$Message.success({
          content: '打包成功',
          duration: 5,
          background: true
        })
      }
    },
    dropFileBbcResponse (event, response) {
      if (response.code == 200) {
        this.$Message.success({
          content: '添加成功',
          duration: 5,
          background: true
        })
        this.$store.dispatch('modulePlugins/add', {
          type: 'local',
          data: response.data
        })
      } else {
        this.$Message.error({
          content: response.message || '添加失败',
          duration: 5,
          background: true
        })
      }
    },
    dropFileBbtResponse (event, response) {
      if (response.code == 200) {
        this.$Message.success({
          content: '添加成功',
          duration: 5,
          background: true
        })
        this.$store.dispatch('modulePlugins/add', {
          type: 'package',
          data: response.data
        })
      } else {
        this.$Message.error({
          content: response.message || '添加失败',
          duration: 5,
          background: true
        })
      }
    },
    pluginInstallResponse (event, response) {
      if (response.data && response.data.pid) {
        if (response.step == 1 && response.data && response.data.pid) {
          // 安装完成
          this.$Message.success({
            content: '安装成功',
            background: true
          })
          this.$store.dispatch('modulePlugins/remove', {
            type: 'downloading',
            data: response.data
          })
          this.$store.dispatch('modulePlugins/add', {
            type: 'normal',
            data: response.data
          })
        } else if (response.step == -1) {
          this.$Message.error({
            content: response.message || '安装失败',
            background: true
          })
          this.$store.dispatch('modulePlugins/remove', {
            type: 'downloading',
            data: response.data
          })
        } else {

          this.$store.dispatch('modulePlugins/add', {
            type: 'downloading',
            data: response.data
          })
        }
      }
    },
    pluginReloadResponse (event, response) {
      if (response.code == 200) {
        this.$Message.success({
          content: '插件重载成功',
          duration: 5,
          background: true
        })
        this.$store.dispatch('modulePlugins/update', {
          type: response.data.type,
          data: response.data
        })
      } else {
        this.$Message.error({
          content: '插件重载失败',
          duration: 5,
          background: true
        })
      }
    },
    pluginRemoveResponse (event, response) {
      if (response.code == 200) {
        this.$Message.success({
          content: '删除成功',
          duration: 5,
          background: true
        })
        this.$store.dispatch('modulePlugins/remove', {
          type: response.data.type,
          data: response.data
        })
      } else {
        this.$Message.error({
          content: '删除失败',
          duration: 5,
          background: true
        })
      }
    },
    pluginUpgradeResponse (event, response) {
      if (response.data && response.data.pid) {
        if (response.step == 0) {
          this.$store.dispatch('modulePlugins/add', {
            type: 'upgrading',
            data: response.data
          })
        } else {
          this.$store.dispatch('modulePlugins/remove', {
            type: 'upgrading',
            data: response.data
          })

          if (response.step == 1) {
            this.$store.dispatch('modulePlugins/remove', {
              type: 'needUpgrade',
              data: response.data
            })
            this.$store.dispatch('modulePlugins/init')
            this.$Message.success({
              content: '更新成功',
              background: true
            })
          } else if (response.step == -1) {
            this.$Message.error({
              content: response.message || '更新失败',
              background: true
            })
          } else { }
        }
      }
    },
    pluginUninstallResponse (event, response) {
      if (response.step == 1) {
        // 卸载成功
        this.$Message.success({
          content: '卸载成功',
          background: true
        })
        this.$store.dispatch('modulePlugins/remove', {
          type: 'normal',
          data: response.data
        })
        this.$store.dispatch('modulePlugins/remove', {
          type: 'downloading',
          data: response.data
        })
        this.$store.dispatch('modulePlugins/remove', {
          type: 'upgrading',
          data: response.data
        })
        this.$store.dispatch('modulePlugins/remove', {
          type: 'needUpgrade',
          data: response.data
        })
      } else if (response.step == -1) {
        // 卸载失败
        this.$Message.error({
          content: response.message || '卸载失败',
          background: true
        })
      } else { }
    },
    getSettings (name) {
      let response = bbtools.sendSync('list-plugins-settings')
      if (name) {
        return response[name] || null
      } else {
        return response
      }
    },
    settingsUpdated (event, settings) {
      this.settings = settings || {}
    },
    upgradePlugin (item) {
      // if (this.upgradeList.hasOwnProperty(item.pid)) return
      // this.upgradeList[item.pid] = item
      // this.$set(this.upgradeList, item.pid, item)
      this.$store.dispatch('modulePlugins/add', {
        type: 'needUpgrade',
        data: item
      })
      // eventBus.$emit('upgrade-plugin', item)
    },
    autoUpgradeHandler (e) {
      switch (e.data.event) {
        case 'upgrade-plugin':
          this.upgradePlugin(e.data.data)
          break
        default:
          break
      }
    },
    pluginListResponse (event, response) {
      if (response.list && response.list.length > 0) {
        this.$store.dispatch('moduleInstalled/init', response.list || [])

      }

      // if (this.settings.autoUpgrade) {
      //   this.autoUpgrade && this.autoUpgrade.postMessage({
      //     event: 'set-installed-plugins',
      //     data: {
      //       list: response || []
      //     }
      //   })
      // }
    },
    categoryListResponse (event, response) {
      // if (this.settings.autoUpgrade) {
      //   let allPlugins = response.reduce((prev, curr) => {
      //     prev = prev.concat(curr.list || [])
      //     return prev
      //   }, [])

      //   this.autoUpgrade && this.autoUpgrade.postMessage({
      //     event: 'set-all-plugins',
      //     data: {
      //       list: allPlugins || []
      //     }
      //   })
      // }
      if (response.code == 200) {
        this.$store.dispatch('moduleCategory/init', {
          categories: response.data.list || []
        })
        let allPlugins = response.data.list.reduce((prev, curr) => {
          prev = prev.concat(curr.list || [])
          return prev
        }, [])

        this.autoUpgrade && this.autoUpgrade.postMessage({
          event: 'set-all-plugins',
          data: {
            list: allPlugins || []
          }
        })

      }
    },
    findIndexByName (name) {
      let _index = -1
      for (let i = 0; i < this.tabs.length; i++) {
        if (this.tabs[i].name == name) {
          _index = this.tabs.length
        }
      }
      return _index
    },
    changeTab (params) {
      if (!params || !params.name) return
      this.activeTab = params.name
      this.urlParams = params.urlParams || {}
    },
    filterChanged (event, params) {
      // console.log('filter changed: ', params)
    },
    initLoginInfo () {
      this.loginInfo = this.$initLoginInfo()
    },
    loginOutResponse () {
      this.loginInfo = {}
    },
    loginResponse (event, res) {
      if (res.status === 200) {
        // 登录成功
        this.loginInfo = res.data
      } else {
        // 登录失败
      }
    },
    hideDropOverlay () {
      this.dropStep = 0
      this.showOverlay = false
      this.dropFiles = []
    },
    drop (e) {
      e.preventDefault()
      e.stopPropagation()
      if (['Package', 'Developer'].indexOf(this.activeTab) > -1) {
        this.dragendEle = null
        eventBus.$emit('drop', e)
        this.dropStep = 1
        this.dropFiles = Array.from(e.dataTransfer.files).map(item => item.path) || []
      }
    },
    dragover (e) {
      e.preventDefault();
      e.stopPropagation();
      if (['Package', 'Developer'].indexOf(this.activeTab) > -1) {
        eventBus.$emit('dragover', e)
        this.showOverlay = true
        this.dropStep = 0
      }
    },
    dragenter (e) {
      e.preventDefault();
      e.stopPropagation();
      if (['Package', 'Developer'].indexOf(this.activeTab) > -1) {
        this.dragendEle = e.target
        eventBus.$emit('dragenter', e)
      }
    },
    dragleave (e) {
      e.preventDefault();
      e.stopPropagation();
      if (['Package', 'Developer'].indexOf(this.activeTab) > -1) {
        if (this.dragendEle == e.target) {
          eventBus.$emit('dragleave', e)
          this.showOverlay = false
        }
      }
    }
  }
}
</script>

<style lang="less">
@import url("./themes/index.less");
* {
  margin: 0;
  padding: 0;
  outline: none;
}
html,
body {
  height: 100%;
}
#app {
  position: relative;
  height: 100%;
  user-select: none;
}
.drag {
  -webkit-app-region: drag !important;
}
.disable-drag {
  -webkit-app-region: no-drag !important;
}

.app_header {
  width: 100%;
  height: 36px;
  background-color: #ffffff;
  cursor: move;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}
.app_content {
  width: 100%;
  // height: calc(~"100% - 36px");
  overflow-y: auto;
}
.overlay_container {
  position: absolute;
  left: 0;
  top: 37px;
  z-index: 999;
  width: 100%;
  height: calc(~"100% - 37px");
  background-color: rgba(255, 255, 255, 0.3);
}

.ivu-tabs-bar {
  margin-bottom: 0 !important;
  border-bottom: 1px solid lighten(@darkDividerColor, 50) !important;
}
.ivu-tabs-content {
  height: 100%;
}
img {
  -webkit-user-drag: none;
}
.main_info {
  // height: calc(~"100% - 30px");
  .ivu-tabs {
    height: 100%;
  }
  .ivu-tabs-content {
    height: calc(~"100% - 36px");
  }
}
.clr {
  .ivu-input {
    border: none !important;
    background-color: transparent !important;
    color: @lightTextColor3;
    &:focus {
      border-color: transparent !important;
      box-shadow: none !important;
    }
    &:hover {
      border-color: transparent !important;
    }
    &::placeholder {
      color: @lightTextColor4;
    }
  }
}

@font-face {
  font-family: "webfont";
  font-display: swap;
  src: url("assets/font/webfont.woff") format("woff"),
    /* chrome、firefox */ url("assets/font/webfont.ttf") format("truetype"); /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
}

@keyframes myMove {
  0% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-24px);
  }
  51% {
    opacity: 0;
    transform: translateY(24px);
  }
  52% {
    opacity: 1;
  }

  100% {
    transform: translateY(0);
  }
}

.plugin_upgrade {
  &.active {
    .plugin_upgrade_icon {
      animation: myMove 1.5s linear infinite;
      animation-fill-mode: forwards;
    }
  }
}

.swiper {
  height: 100%;
  width: 100%;

  .swiper-slide {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-weight: bold;
  }
}

.env_container {
  .ivu-timeline-item-head {
    margin-top: 3px;
  }
  .ivu-timeline-item-head-custom {
    margin-top: 10px;
  }
}
</style>
